import { defineComponent, onMounted, reactive, ref, nextTick } from 'vue'
import type { lamppostStateType, treeMenuType } from './typings'
import {
  ElLink,
  ElMessageBox,
  ElMessage,
  ElScrollbar,
  ElTree,
  ElSpace,
  ElCard,
  ElDivider,
  ElLoading
} from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

import RunMap from './runMap'
import { useStore } from 'vuex'

import styles from '../../index.module.scss' /** 样式 */
import PostModel from './postModel'
import DimModel from '../../components/dimModel'
import LampModel from './lampModel'
import treeGroup from '~/assets/singleLamp/tree_group.png'
// import treeLamp from '~/assets/singleLamp/tree_lamp.png'
// import treePost from '~/assets/singleLamp/tree_denggan.png'
import lamppostTwo from '~/assets/singleLamp/ic_lamp_2.png'
import singleLampSrc from '~/assets/singleLamp/ic_singleLamp.png'
// 单灯运行地图
export default defineComponent(function LampRunMap() {
  const store = useStore()
  // 定义变量
  const state = reactive<lamppostStateType>({
    modalVisible: false, // 灯杆弹窗
    id: '',
    areaVisible: true, // 左侧树
    lamppostTreeData: [],
    lamppostTreeProps: {
      label: 'title',
      children: 'children'
    },
    polygonShowDetail: [],
    mapZoom: 14,
    graphicExampleExpand: false,
    menuVisible: false,
    clickTreeMenuRes: [
      { name: '开灯', type: 1 },
      { name: '关灯', type: 0 },
      { name: '调光', type: 2 }
    ],
    treeRigClickMenuSet: {
      x: 0,
      y: 0,
      view: false
    },
    dimVisible: false,
    lampVisible: false // 单灯弹窗
  })
  const PostModelRef = ref()
  const LampModelRef = ref()
  const treeLamppostRef = ref()
  const runMapRef = ref()
  const dimModelRef = ref()
  const ulRef = ref()
  // 初始化灯杆树数据
  const initLamppostTree = async () => {
    const res = await store.dispatch('singleLamp/GetPostTree')
    if (res?.code === 200) {
      state.lamppostTreeData = res.data
    }
  }
  // 获取当前地图层级并赋值
  const getMapZoom = () => {
    state.mapZoom = Math.round(runMapRef.value.map.getZoom())
  }

  // 获取当前页面初始化所需要的地图数据
  const initCallback = async () => {
    getMapZoom()
    runMapRef.value.handleSetMapInfo()
    markerLabelsLayerAjax()
  }
  // 控制地图放大缩小
  const handleClickChangeMapZoom = async (type: '+' | '-') => {
    if (type === '+') {
      state.mapZoom++
    } else {
      state.mapZoom--
    }
    await runMapRef.value.map.setZoom(state.mapZoom)
  }

  const loadRef = ref<LoadingInstance>()
  //  地图灯杆数据
  const markerLabelsLayerAjax = async () => {
    loadRef.value = ElLoading.service({
      target: '#loadRef',
      background: 'rgba(255, 255, 255, .2)',
      text: '加载中'
    })

    const { code, data } = await store.dispatch('singleLamp/GetPostPositionData')
    if (code === 200 && data.length > 0) {
      runMapRef.value.markerLabelsLayer(data)
      loadRef.value!.close()
    } else {
      runMapRef.value.markerLabelsLayer([])
    }
    loadRef.value!.close()
  }
  // 点击地图上的灯杆
  const handleLamppostInfo = (row: any) => {
    state.modalVisible = true
    state.lampVisible = false
    nextTick(() => {
      PostModelRef.value.open(row)
    })
  }
  // 点击树节点
  const handleClick = (node: any) => {
    state.menuVisible = false
    // 灯杆
    if (node.type === 'post') {
      state.modalVisible = true
      state.lampVisible = false
      nextTick(() => {
        PostModelRef.value.open(node)
        const markers = [node.lon, node.lat]
        const content = node.title
        const num = node.value * 1
        runMapRef.value.markerLayer({ markers, content, num })
      })
      // 单灯
    } else if (node.type === 'lampNode') {
      state.lampVisible = true
      state.modalVisible = false
      nextTick(() => {
        LampModelRef.value.open(node)
      })
    }
  }
  // 右键点击节点
  const handleRightClick = (event: any, data: any, node: any) => {
    if (!node || (node.child && node.child.length === 0)) {
      return
    }
    event.stopPropagation()
    if (data.type === 'group') {
      event.preventDefault()
      state.menuVisible = true
      const obj = {
        x: event.clientX,
        y: event.clientY,
        view: true,
        data
      }
      if (event.clientY > 700) {
        obj.y = event.clientY - 100
      }
      state.groupId = data.id
      state.treeRigClickMenuSet = obj
    }
  }
  //  隐藏右键菜单
  // const onBodyMouseDown = (event:any) => {
  //   // console.log(event)
  //   // if(event.target.parents('.tree-rig-click-menu').length > 0){
  //     // state.menuVisible = false
  //   // }
  // }
  const clickMenuEvent = (type: number) => {
    let text = ''
    if (type === 1) {
      text = '确认对选中的分组下发开灯命令？'
    } else if (type === 0) {
      text = '确认对选中的分组下发关灯命令？'
    } else if (type === 2) {
      text = '确认对选中的分组下发调光命令？'
    }

    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>{<p class="delete-title">{text}</p>}</section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        if (type === 1 || type === 0) {
          await store
            .dispatch('singleLamp/GroupSwitchLight', { groupId: state.groupId, opr: type })
            .then(async (result) => {
              if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
            })
        } else {
          state.dimVisible = true
        }
      })
      .catch(() => {})
  }
  const close = () => {
    state.modalVisible = false
  }
  const lampclose = () => {
    state.lampVisible = false
  }
  // 分组调光
  const dimLight = async () => {
    const dimNum = dimModelRef.value.ruleForm.dimNum
    const res = await store.dispatch('singleLamp/GroupDim', { groupId: state.groupId, dim: dimNum })
    if (res.code === 200) {
      ElMessage({
        message: '操作成功',
        type: 'success',
        duration: 2000
      })
    }
  }
  const dimClose = () => {
    state.dimVisible = false
  }
  // 初始化
  onMounted(async () => {
    initLamppostTree()

    // document.body.addEventListener('mousedown',e=>{
    //   onBodyMouseDown(e)
    // })
  })

  return () => (
    <section class={styles.sessionDom}>
      <RunMap
        id={styles['map-init']}
        ref={runMapRef}
        initCallback={initCallback}
        getMapZoom={getMapZoom}
        onHandleLamppostInfo={handleLamppostInfo}
      />
      {state.areaVisible && (
        <div class={styles.areaDom}>
          <div class={styles.areaTitle}>灯杆列表</div>
          <div class={styles.app}>
            <ElScrollbar class={styles['runmap-scrollbar']}>
              <ElTree
                ref={treeLamppostRef}
                data={state.lamppostTreeData}
                props={state.lamppostTreeProps}
                nodeKey="id"
                highlight-current
                onNode-click={(data) => handleClick(data)}
                onNode-contextmenu={(event, data, node) => handleRightClick(event, data, node)}
                v-slots={{
                  default: ({ node }: any) => (
                    <span style="display:flex">
                      {node.data.type === 'group' && <img src={treeGroup} alt="" />}
                      {node.data.type === 'post' && <img src={lamppostTwo} alt="" />}
                      {node.data.type === 'lampNode' && <img src={singleLampSrc} alt="" />}
                      {node.label}
                    </span>
                  )
                }}
              ></ElTree>
            </ElScrollbar>
            <div class="scrollbar"></div>
          </div>
        </div>
      )}
      {state.modalVisible && (
        <PostModel cancel={close} ref={PostModelRef} initLamppostTree={initLamppostTree} />
      )}
      {state.lampVisible && <LampModel cancel={lampclose} ref={LampModelRef} />}
      {state.menuVisible && (
        <ul
          class={styles['tree-rig-click-menu']}
          ref={ulRef}
          style={{
            left: `${state.treeRigClickMenuSet.x}px`,
            top: `${state.treeRigClickMenuSet.y}px`
          }}
        >
          {state?.clickTreeMenuRes.map((item: treeMenuType) => (
            <li onClick={() => clickMenuEvent(item.type!)}>
              <label>{item.name}</label>
            </li>
          ))}
        </ul>
      )}
      {state.dimVisible && <DimModel ref={dimModelRef} onSubmitForm={dimLight} cancel={dimClose} />}
      {/* 控制地图放大缩小 */}
      <section
        // direction="vertical"
        class={{
          [styles['asset-home-zoom']]: true,
          [styles['asset-home-zoom-expand']]: state.graphicExampleExpand
        }}
      >
        <ElCard class="zoom-number-card">{state.mapZoom}</ElCard>
        <ElCard class="zoom-option-card">
          <ElSpace direction="vertical" spacer={<ElDivider />}>
            <ElLink
              underline={false}
              icon={Plus}
              disabled={state.mapZoom === 20}
              onClick={() => handleClickChangeMapZoom('+')}
            />
            <ElLink
              underline={false}
              icon={Minus}
              disabled={state.mapZoom === 5}
              onClick={() => handleClickChangeMapZoom('-')}
            />
          </ElSpace>
        </ElCard>
      </section>
    </section>
  )
})
